class_name CardStateMachine
extends Node

# 导出变量 基本状态 作用：存储状态机的初始状态，起始状态
@export var initial_state: CardState
# 当前状态
var current_state: CardState
# 状态字典： 存储状态机中所有可用状态
var states := {}

# 迭代状态机所有子节点，判断当前子节点是否为卡牌状态; 如果是，存入状态字典，连接信号做状态变化处理
func init(card: CardUI) -> void:
	for child in get_children():
		if child is CardState:
			states[child.state] = child
			child.transition_requested.connect(_on_transition_requested)
			child.card_ui = card
	
	# 如果有初始状态，则进入该状态，设置当前状态为该初始状态
	if initial_state:
		initial_state.enter()
		current_state = initial_state


# 输入事件, 如果有当前状态，则调用这个状态的输入回调函数
func on_input(event: InputEvent) -> void:
	if current_state:
		current_state.on_input(event)
	pass
	
# GUI输入事件， 如果有当前状态，则调用这个状态的输入回调函数
func on_gui_input(event: InputEvent) -> void:
	if current_state:
		current_state.on_gui_input(event)
	pass


# 鼠标进入
func on_mouse_entered()-> void:
	if current_state:
		current_state.on_mouse_entered()
	pass
	
# 鼠标退出	
func on_mouse_exited()-> void:
	if current_state:
		current_state.on_mouse_exited()
	pass	

# 状态改变处理函数
func _on_transition_requested(from: CardState, to: CardState.State) -> void:
	# 如果from 状态和当前状态不相同，则return; 
	if from != current_state:
		return
	# 如果相同，从状态字典中存储对新状态的引用
	var new_state: CardState = states[to]
	# 如果新状态存在，则退出当前状态；不存在则return
	if not new_state:
		return
			
	if current_state:
		current_state.exit()
	
	# 进入新状态，并设置当前状态为新状态
	new_state.enter()
	current_state = new_state
	
